package com.yuke.cloud.service.cmc.controller.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuke.cloud.common.base.constant.GlobalConstant;
import com.yuke.cloud.common.base.dto.MsgNotificationBody;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.PublicUtil;
import com.yuke.cloud.common.util.RedisKeyUtil;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.cmc.dto.*;
import com.yuke.cloud.service.api.cmc.service.CmcFeignApi;
import com.yuke.cloud.service.api.opc.service.OpcSendNotifyFeignApi;
import com.yuke.cloud.service.cmc.entity.CmsCoupon;
import com.yuke.cloud.service.cmc.entity.CmsCouponReceive;
import com.yuke.cloud.service.cmc.entity.CmsSysInfo;
import com.yuke.cloud.service.cmc.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>Company: Copyright (c) 2018. yuke All Rights Reserved. </br> </p>
 * <p>Title：yukemall </br> </p>
 * <p>com.yuke.cloud.service.cmc.controller.rpc Description TODO </br> </p>
 * @Author wg
 * @Date   2019/6/4 13:23
 */
@Slf4j
@RestController
@Api(value = "API - CmcSecKillFeignClient", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class CmcFeignClient extends BaseController implements CmcFeignApi {

    @Resource
    CmsSecKillService cmsSecKillService;
    @Resource
    CmsSecKillSkuService cmsSecKillSkuService;
    @Resource
    CmsCouponReceiveService cmsCouponReceiveService;
    @Resource
    CmsCouponSpecService cmsCouponSpecService;
    @Resource
    CmsRedReceiveService cmsRedReceiveService;
    @Resource
    CmsCouponService cmsCouponService;
    @Resource
    CmsSysInfoService cmsSysInfoService;
    @Resource
    private CmsAppTopicService cmsAppTopicService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private OpcSendNotifyFeignApi opcSendNotifyFeignApi;



    @Override
    @ApiOperation(httpMethod = "GET", value = "将还没有开始的秒杀活动及商品(一般24小时内)进行缓存")
    public Wrapper loadSecKillAndSpecs() {
        System.out.println("没有开始的秒杀活动及商品(一般24小时内)进行缓存");
       // List<CmsSecKillAndSkuDto> cmsSecKillAndSkuDtos = cmsSecKillService.getNextSecKillAndSpecs();
        List<CmsSecKillAndSkuDto> cmsSecKillAndSkuDtos = cmsSecKillService.getSecKillAndSpecs();
        System.out.println(cmsSecKillAndSkuDtos);
        if (cmsSecKillAndSkuDtos != null && cmsSecKillAndSkuDtos.size() > 0) {

            for (CmsSecKillAndSkuDto cmsSecKillAndSkuDto : cmsSecKillAndSkuDtos) {
                CmsSecKillDto cmsSecKillDto = cmsSecKillAndSkuDto.getCmsSecKillDto();
                Date now = new Date();
                long timeOut = cmsSecKillAndSkuDto.getCmsSecKillDto().getEndTime().getTime() - now.getTime();
                redisTemplate.opsForValue().set(RedisKeyUtil.getSecKillKey(String.valueOf(cmsSecKillDto.getSecKillId())),
                        cmsSecKillDto, timeOut, TimeUnit.MILLISECONDS);

                List<CmsSecKillSkuDto> cmsSecKillSkuDtos = cmsSecKillAndSkuDto.getCmsSecKillSkuDtos();
                if (cmsSecKillSkuDtos != null && cmsSecKillSkuDtos.size() > 0) {
                    for (CmsSecKillSkuDto cmsSecKillSkuDto : cmsSecKillSkuDtos) {
                        redisTemplate.opsForValue().set(RedisKeyUtil.getSecKillSkuKey(String.valueOf(cmsSecKillSkuDto.getSecKillId()),
                                String.valueOf(cmsSecKillSkuDto.getSecKillSkuId())), cmsSecKillSkuDto, timeOut, TimeUnit.MILLISECONDS);
                    }
                }
            }
        }

        return WrapMapper.ok();
    }

    @Override
    @ApiOperation(httpMethod = "POST", value = "更新秒杀活动商品的库存")
    public Wrapper updateSecKillSkuCount(@RequestParam(value = "secKillId") Long secKillId, @RequestParam(value = "specId") Long specId,
                                         @RequestParam(value = "number") Integer number, @RequestParam(value = "lockNumber") Integer lockNumber,
                                         @RequestParam(value = "saledNumber") Integer saledNumber) {

        cmsSecKillSkuService.updateStorageIncrement(secKillId, specId, number, lockNumber, saledNumber);
        return WrapMapper.ok();
    }

    @Override
    @ApiOperation(httpMethod = "POST", value = "更新秒杀活动商品的库存")
    public Wrapper updateSecKillSkusCount(@RequestBody List<CmsSecKillSkuDto> cmsSecKillSkuDtos) {

        for (CmsSecKillSkuDto cmsSecKillSkuDto : cmsSecKillSkuDtos) {
            cmsSecKillSkuService.updateStorageIncrement(cmsSecKillSkuDto.getSecKillId(), cmsSecKillSkuDto.getSpecId(),
                    cmsSecKillSkuDto.getStoreCount(), cmsSecKillSkuDto.getLockCount(), cmsSecKillSkuDto.getSaledCount());
            System.out.println(cmsSecKillSkuDto);
        }

        return WrapMapper.ok();
    }

    //添加商家注册优惠券
    //addCouponReceive
    @Override
    @ApiOperation(httpMethod = "POST", value = "更新")
    public Wrapper addCouponReceive(@RequestParam(value = "shopId") Long shopId,
                                    @RequestParam(value = "sendType") Integer sendType,
                                    @RequestParam(value = "sendAspect") Integer sendAspect) {
        //
        //查找优惠券Id

        Example example = new Example(CmsCoupon.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("sendType", sendType);
        criteria.andEqualTo("sendAspect", sendAspect);
        criteria.andEqualTo("tag", 0);
        criteria.andCondition("number - now_num > 0");
        Date now = new Date();
        criteria.andCondition(" UNIX_TIMESTAMP( send_start_date ) <= " + now.getTime() / 1000 + " AND " + now.getTime() / 1000
                + " <= UNIX_TIMESTAMP( send_end_date ) ");

        List<CmsCoupon> cmsCoupon = cmsCouponService.selectByExample(example);
        log.info("合适的优惠券{}",cmsCoupon);
        //有发放的券才会发放
        if (cmsCoupon == null || cmsCoupon.size()<1) {
            return WrapMapper.error("当前没有合适的优惠券！");
        }

        CmsCouponReceive cmsCouponReceive = new CmsCouponReceive();
        cmsCouponReceive.setCouponId(cmsCoupon.get(0).getCouponId());
        cmsCouponReceive.setReceiveId(shopId);
        Integer oneR = cmsCouponReceiveService.selectCount(cmsCouponReceive);
        if (oneR >= cmsCoupon.get(0).getMinTransmitNum()){
            System.out.println("该优惠券已经领取！");
            return WrapMapper.error("该优惠券已经领取！");
        }

        cmsCouponReceive.setSourceKey((byte) 1);

        if (sendAspect.equals(1)){ //商家
            cmsCouponReceive.setReceiveType((byte) 1); //商铺
        }else{
            cmsCouponReceive.setReceiveType((byte) 0); //个人用户
        }
        cmsCouponReceive.setReceiveType((byte) 1);
        //cmsCouponReceive.setReferer(getLoginAuthDto().getUserId().toString());
        cmsCouponReceive.setReferer(shopId.toString());
        cmsCouponReceive.setCouponStatus((byte) 0);

        if (cmsCouponReceiveService.save(cmsCouponReceive)<1){
            return WrapMapper.error("优惠券保存失败！");
        }
        System.out.println("优惠券2#发放成功！");
        cmsCoupon.get(0).setNowNum(cmsCoupon.get(0).getNowNum()+1);
        cmsCoupon.get(0).setUpdateTime(new Date());
        cmsCouponService.update(cmsCoupon.get(0));

        byte receiveType;
        if (sendAspect.equals(1)){
            receiveType = 2;
        }else{
            receiveType = 1;
        }
        String title = "系统消息";
        String content = "系统给您发放了一张优惠券，快去使用吧！";
        MsgNotificationBody msgNotificationBody = new MsgNotificationBody();
        msgNotificationBody.setReceiveType(receiveType);
        msgNotificationBody.setMsgType("shopMsg");
        msgNotificationBody.setTitle(title);
        msgNotificationBody.setContent(content);
        msgNotificationBody.setTime(new Date());
        opcSendNotifyFeignApi.sendnotify(shopId.toString(), title, content, 0);
        return WrapMapper.ok();

    }

    //获得满减标准
    @Override
    public Map<String,String> getMonthRebate(@RequestParam(value = "groupId") Long groupId){
        Example example = new Example(CmsSysInfo.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("groupId",groupId);
        criteria.andEqualTo("sysInfoType",GlobalConstant.SysInfo.SYS_INFO_MONTHREBATE);
        List<CmsSysInfo> cmsSysInfoList = cmsSysInfoService.selectByExample(example);
        if (PublicUtil.isEmpty(cmsSysInfoList)){
            logger.info("系统信息查询失败！");
            return null;
        }
        CmsSysInfo cmsSysInfo = cmsSysInfoList.get(0);
        Map<String,String> map = new HashMap<String, String>();
        if (cmsSysInfo!=null && cmsSysInfo.getStatus()>0) {
            JSONObject jsonObject = JSON.parseObject(cmsSysInfo.getInfoValue());
            Iterator<String> iter = jsonObject.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                map.put(key, jsonObject.getString(key));
            }
        }
        return map;
    }


    //更新商家优惠券状态到已使用
    @Override
    @ApiOperation(httpMethod = "POST", value = "更新")
    public Wrapper updateCouponReceive(@RequestParam(value = "id") Long id,@RequestParam(value = "orderId") Long orderId) {
        //
        if (id!=null){
            System.out.println(id);
            cmsCouponReceiveService.modifyCouponStatus(id,orderId);
        }else{
            return WrapMapper.error("优惠券状态更新错误！");
        }
        return WrapMapper.ok();
    }

    //更新商家优惠券状态到未使用
    @Override
    @ApiOperation(httpMethod = "POST", value = "更新")
    public Wrapper updateCouponReceiveBack(@RequestParam(value = "id") Long id) {
        //
        if (id!=null){
            System.out.println(id);

            cmsCouponReceiveService.updateCouponStatus(id);

        }else{
            return WrapMapper.error("优惠券状态更新错误！");
        }
        return WrapMapper.ok();
    }

    @Override
    @ApiOperation(httpMethod = "POST", value = "更新")
    public Long findCouponReceiveIdByOrderId(@RequestParam(value = "orderId") Long orderId) {
        //
        Long couponReceiveId = 0L;
        if (orderId!=null){
            System.out.println(orderId);
            CmsCouponReceive cmsCouponReceive = new CmsCouponReceive();
            cmsCouponReceive.setOrderId(orderId);
            cmsCouponReceive = cmsCouponReceiveService.selectOne(cmsCouponReceive);
            if (cmsCouponReceive != null){
                couponReceiveId = cmsCouponReceive.getCouponReceiveId();
            }
        }
        return couponReceiveId;
    }

    @Override
    public CmsSysInfoDto getSysInfoDtoByType(@RequestParam(value = "groupId") Long groupId,@RequestParam(value = "typeId")Integer typeId) {
        CmsSysInfoDto cmsSysInfoDto = new CmsSysInfoDto();
        Example example = new Example(CmsSysInfo.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("groupId",groupId);
        criteria.andEqualTo("sysInfoType",typeId);
        List<CmsSysInfo> cmsSysInfoList = cmsSysInfoService.selectByExample(example);
        if (PublicUtil.isEmpty(cmsSysInfoList)){
            logger.info("系统信息查询失败！");
            return null;
        }
        CmsSysInfo cmsSysInfo = cmsSysInfoList.get(0);

        if (cmsSysInfo != null && cmsSysInfo.getId()>0){
            BeanUtils.copyProperties(cmsSysInfo,cmsSysInfoDto);
        }
        return cmsSysInfoDto;
    }

    @Override
    public Wrapper updateRedReceiveUsered(@RequestParam(value = "redReceiveId") Long redReceiveId,
                                          @RequestParam(value = "orderIds") String orderIds) {
        Integer num = cmsRedReceiveService.updateRedReceiveUsered(redReceiveId,orderIds);
        return WrapMapper.ok(num);
    }

    @Override
    public List<CmsTopicDto> getTopicInfoByTopicIds(@RequestBody  List<Long> topicIds){
        if (topicIds != null && topicIds.size() > 0){
            return cmsAppTopicService.getTopicInfoByTopicIds(topicIds);
        }
        return null;
    }

    //添加商家注册优惠券
    //addCouponReceive
    @Override
    @ApiOperation(httpMethod = "POST", value = "更新")
    public Wrapper addCouponActive(@RequestParam(value = "shopId") Long shopId,
                                    @RequestParam(value = "sendType" ,defaultValue = "0") Integer sendType,
                                    @RequestParam(value = "sendAspect") Integer sendAspect,
                                   @RequestParam(value = "couponId" ,defaultValue = "0") Long couponId) {
        //
        //查找优惠券Id

        Example example = new Example(CmsCoupon.class);
        Example.Criteria criteria = example.createCriteria();
        if (sendType != null && sendType > 0){
            criteria.andEqualTo("sendType", sendType);
        }
        if (couponId != null && couponId > 0){
            criteria.andEqualTo("couponId", couponId);
        }

        criteria.andEqualTo("sendAspect", sendAspect);
        criteria.andEqualTo("tag", 0);
        //criteria.andCondition("number - now_num > 0");
        Date now = new Date();
        criteria.andCondition(" UNIX_TIMESTAMP( send_start_date ) <= " + now.getTime() / 1000 + " AND " + now.getTime() / 1000
                + " <= UNIX_TIMESTAMP( send_end_date ) ");

        List<CmsCoupon> cmsCoupon = cmsCouponService.selectByExample(example);
        log.info("合适的优惠券{}",cmsCoupon);
        //有发放的券才会发放
        if (cmsCoupon == null || cmsCoupon.size()<1) {
            return WrapMapper.error("当前没有合适的优惠券！");
        }

        CmsCouponReceive cmsCouponReceive = new CmsCouponReceive();
        cmsCouponReceive.setCouponId(cmsCoupon.get(0).getCouponId());
        cmsCouponReceive.setReceiveId(shopId);
        Integer oneR = cmsCouponReceiveService.selectCount(cmsCouponReceive);
        if (oneR >= cmsCoupon.get(0).getMinTransmitNum()){
            System.out.println("该优惠券已经领取！");
            return WrapMapper.error("该优惠券已经领取！");
        }

        cmsCouponReceive.setSourceKey((byte) 1);

        if (sendAspect.equals(1)){ //商家
            cmsCouponReceive.setReceiveType((byte) 1); //商铺
        }else{
            cmsCouponReceive.setReceiveType((byte) 0); //个人用户
        }
        cmsCouponReceive.setReceiveType((byte) 1);
        //cmsCouponReceive.setReferer(getLoginAuthDto().getUserId().toString());
        cmsCouponReceive.setReferer(shopId.toString());
        cmsCouponReceive.setCouponStatus((byte) 0);

        if (cmsCouponReceiveService.save(cmsCouponReceive)<1){
            return WrapMapper.error("优惠券保存失败！");
        }
        System.out.println("优惠券发放成功！");
        cmsCoupon.get(0).setNowNum(cmsCoupon.get(0).getNowNum()+1);
        cmsCoupon.get(0).setUpdateTime(new Date());
        cmsCouponService.update(cmsCoupon.get(0));

        byte receiveType;
        if (sendAspect.equals(1)){
            receiveType = 2;
        }else{
            receiveType = 1;
        }
        String title = "系统消息";
        String content = "系统给您发放了一张优惠券，快去使用吧！";
        MsgNotificationBody msgNotificationBody = new MsgNotificationBody();
        msgNotificationBody.setReceiveType(receiveType);
        msgNotificationBody.setMsgType("shopMsg");
        msgNotificationBody.setTitle(title);
        msgNotificationBody.setContent(content);
        msgNotificationBody.setTime(new Date());
        opcSendNotifyFeignApi.sendnotify(shopId.toString(), title, content, 0);
        return WrapMapper.ok();

    }

    @Override
    @ApiOperation(httpMethod = "POST", value = "更新")
    public List<CmsCouponUserDto> getCouponUserListByCondition(@RequestBody CmsCouponUserDto cmsCouponReceive){
        List<CmsCouponUserDto> list = cmsCouponReceiveService.getCouponUserListByCondition(cmsCouponReceive);
        return list;
    }

    @Override
    public List<CmsCouponGoodsDto> getCouponGoodsByCouponId(Long couponId){
        return cmsCouponSpecService.getCouponGoodsByCouponId(couponId);
    }
}
